<template>
	<div class="card-header-box1">
		<el-form ref="queryForm" :inline="true" :model="queryParams" :rules="rules">
			<el-form-item prop="releaseTime" label="发布时间:" style="margin-left: 20px">
				<el-date-picker
					v-model="queryParams.releaseTime"
					type="date"
					value-format="YYYY-MM-DD HH:mm:ss"
					format="YYYY-MM-DD"
					style="width: 100%"
					:disabled="!getedit"
				/>
			</el-form-item>

			<el-form-item prop="job_status" label="阶段状态:" style="margin-left: 20px">
				<div style="color: #666">
					{{
						props.datainfo.progressColor == 'green' || props.datainfo.progressColor == ''
							? '正常'
							: props.datainfo.progressColor == 'orange' || props.datainfo.progressColor == 'red'
								? '滞后'
								: ''
					}}
				</div>
			</el-form-item>

			<el-form-item label="实施时间:" style="margin-left: 20px" prop="implementationTime">
				<el-date-picker
					v-model="queryParams.implementationTime"
					:disabled="!getedit"
					type="date"
					value-format="YYYY-MM-DD HH:mm:ss"
					format="YYYY-MM-DD"
					style="width: 100%"
				/>
			</el-form-item>

			<el-form-item label="标准编号:" style="margin-left: 20px" prop="standardNumber">
				<el-input v-model="queryParams.standardNumber" placeholder="请输入" :disabled="!getedit" />
			</el-form-item>

			<!-- <el-row>

				<el-col :span="24">
					<el-form-item label="标准名称:" style="width: 100%">
						<el-input v-model="queryForm.job_status" placeholder="请输入" />
					</el-form-item>
				</el-col>
			</el-row> -->
		</el-form>

		<div class="titlezi flex">
			<div class="flex-1">本阶段附件</div>
		</div>

		<div class="kuaibj mt20">
			<Cfupload
				v-for="value in fjcodelist"
				:key="value"
				:istable="false"
				:labeltitle="value.definitionName"
				:code="value.businessCode"
				:suffix-type="value.suffixType"
				:filelist="value.uploadedFiles"
				:disabled="getedit"
				:ismust="value.imustUpload"
				@success="handleUploadSuccess"
				@remove="handleFileRemove"
			></Cfupload>
		</div>
		<!-- {{ props.requestParams.progressStatus }} -->
		<div
			v-if="
				Number(props.requestParams.progressStage) == 10 &&
				Number(props.requestParams.progressStatus) < 12 &&
				userStore.user.roleCode.includes('SHZJW') &&
				props.datainfo.edit == 'true'
			"
			class="dialog-footer mt10"
		>
			<el-button type="success" @click="zancunSubmit">暂存</el-button>
			<el-button type="primary" @click="endSubmit">发布</el-button>
		</div>
	</div>
</template>
<script setup lang="ts">
import { ref, defineProps, watch, nextTick, onMounted, computed, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import Cfupload from '@/components/cf-upload/index.vue'
import { router } from '@/router'
import { queryFilesSettingApi, updateStageAndStatusApi, updateProgressApi } from '@/api/bianzhi/index'

import { useDictionaryStore } from '@/store/modules/dictionary'

const emit = defineEmits<{ (event: 'updateData', value: ''): void }>()

const queryParams = ref({ standardNumber: '', progressStage: '', releaseTime: '', implementationTime: '' })
const dictionaryStore = useDictionaryStore()
const jdstatuslist = dictionaryStore.getDictionaryByCode('T007')
const fjcodelist = ref(null)

const datalist = ref([])
const uploadedFiles = ref([])
import { useUserStore } from '@/store/modules/user'
const userStore = useUserStore()
const props = defineProps({
	datainfo: {
		type: Object,
		default: () => ({})
	},
	requestParams: {
		type: Object,
		default: () => ({})
	}
})
const queryForm = ref()

watch(
	() => props.requestParams,
	(newVal: any, oldVal: any) => {
		queryFilesSettingApi({ businessStage: 'ReleaseImplementation' }).then(res => {
			fjcodelist.value = res.data
			nextTick(() => {
				console.log(props.requestParams, 'props.requestParams')
				queryParams.value.standardNumber = props.requestParams.standardNumber ? props.requestParams.standardNumber : ''
				queryParams.value.releaseTime = props.requestParams.releaseTime ? props.requestParams.releaseTime : ''

				queryParams.value.implementationTime = props.requestParams.implementationTime ? props.requestParams.implementationTime : ''

				///  console.log(props.requestParams.solicitOpinionsBeforeFileList.length, '我是大纲附件们' )
				if (props.requestParams.releaseImplementationFileList.length > 0) {
					const aa: any = props.requestParams.releaseImplementationFileList
					uploadedFiles.value = aa //附件上传
					const result = fjcodelist.value.map(itemA => {
						const matchedItem = aa.find(itemB => itemB.remark === itemA.definitionName)
						//	console.log(matchedItem, 'matchedItem')
						if (matchedItem) {
							return { ...itemA, uploadedFiles: [matchedItem] } // 合并相同字段的数据
						}
						return itemA
					})
					fjcodelist.value = result //result赋值给 fjcodelist
				}
			})
		})
	},
	{ immediate: true }
)

const rules = reactive({
	releaseTime: [{ required: true, message: '请选择发布时间', trigger: 'change' }],
	implementationTime: [{ required: true, message: '请选择实施时间', trigger: 'change' }],
	standardNumber: [{ required: true, message: '请输入标准编号', trigger: 'blur' }]
})

const getedit = computed(() => {
	if (Number(props.datainfo.progressStage) == 10) {
		if (props.datainfo.edit == 'true') {
			if (Number(props.requestParams.progressStatus) < 12 && userStore.user.roleCode.includes('SHZJW')) {
				return true
			} else {
				return false
			}
		} else {
			return false
		}
	} else {
		return false
	}
})

const validateBeforeSubmit = (requiredItems, uploadedFiles) => {
	const errors = []

	requiredItems.forEach(item => {
		const uploadedItem = uploadedFiles.some(file => file.remark === item.definitionName)
		if (!uploadedItem && item.imustUpload === 1) {
			errors.push(`【${item.definitionName}】未上传文件`)
		}
	})

	if (errors.length > 0) {
		ElMessage.error(errors.join(','))
		return false
	}

	return true
}
// 处理上传成功事件
const handleUploadSuccess = (data: any) => {
	uploadedFiles.value.push(data) // 将接口返回的数据添加到文件列表
}

// 处理文件删除事件
const handleFileRemove = (file: any) => {
	const id = file.response ? file.response.data.id : file.id
	uploadedFiles.value = uploadedFiles.value.filter(
		item => item.id !== id // 根据 uid 删除对应文件
	)
}

const endSubmit = () => {
	if (!validateBeforeSubmit(fjcodelist.value, uploadedFiles.value)) {
		return
	}
	queryForm.value.validate(valid => {
		if (valid) {
			if (uploadedFiles.value.length > 0) {
				uploadedFiles.value.forEach(item => {
					delete item.name
				})
			}
			const filelist = [...uploadedFiles.value]

			const data = {
				expertsList: [],
				id: props.requestParams.id,
				standardProjectName: props.requestParams.name,
				standardNumber: queryParams.value.standardNumber,
				dgbzReviewTime: props.requestParams.dgbzReviewTime, //大纲评审时间  //大纲评审时间
				zqyjReviewTime: props.requestParams.zqyjReviewTime, //征求意见评审时间
				songsReviewTime: props.requestParams.songsReviewTime, //送审评审时间
				baopCompletionTime: props.requestParams.baopCompletionTime, //报批时间
				releaseTime: queryParams.value.releaseTime, //发布时间
				implementationTime: queryParams.value.implementationTime, //实施时间
				progressCode: 'ReleaseImplementation',
				progressStatus: 12,
				routeName: '/progressInfo',
				filesRecordList: filelist, //所有附件
				mainUnitList: [], //主编单位
				partUnitList: [], //参编单位
				projectMainDrafterList: [] //主要起草人员
			}

			updateStageAndStatusApi(data).then(res => {
				emit('updateData', '')
				ElMessage.success('提交成功')
				// nextTick(() => {
				// 	router.push({
				// 		path: '/bianzhi/shenbao/index'
				// 	})
				// })
			})
		} else {
			console.log('error submit!!')
			return false
		}
	})
}

const zancunSubmit = () => {
	if (uploadedFiles.value.length > 0) {
		uploadedFiles.value.forEach(item => {
			delete item.name
		})
	}
	const filelist = [...uploadedFiles.value]

	const data = {
		expertsList: [],
		id: props.requestParams.id,
		standardProjectName: props.requestParams.name,
		standardNumber: queryParams.value.standardNumber,
		dgbzReviewTime: props.requestParams.dgbzReviewTime, //大纲评审时间  //大纲评审时间
		zqyjReviewTime: props.requestParams.zqyjReviewTime, //征求意见评审时间
		songsReviewTime: props.requestParams.songsReviewTime, //送审评审时间
		baopCompletionTime: props.requestParams.baopCompletionTime, //报批时间
		releaseTime: queryParams.value.releaseTime, //发布时间
		implementationTime: queryParams.value.implementationTime, //实施时间
		progressCode: 'ReleaseImplementation',
		routeName: '/progressInfo',
		filesRecordList: filelist, //所有附件
		mainUnitList: [], //主编单位
		partUnitList: [], //参编单位
		projectMainDrafterList: [] //主要起草人员
	}

	updateProgressApi(data).then(res => {
		emit('updateData', '')
		ElMessage.success('暂存成功')
		// nextTick(() => {
		// 	router.push({
		// 		path: '/bianzhi/shenbao/index'
		// 	})
		// })
	})
}
</script>

<style lang="scss" scoped>
.card-header-box1 {
	display: flex;

	flex-direction: column;

	overflow-y: scroll;
	height: 100%;

	&::-webkit-scrollbar {
		display: none;
	}

	.titlezi {
		font-size: 16px;
		color: #333;
	}

	.kuaibj {
		background-color: #f5f6fa;
		padding: 20px;
		border-radius: 6px;
	}

	.fjsmzi {
		font-size: 12px;
		color: #606266;
		margin-left: 5px;
	}
}
</style>
